<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-10-09
 * Time: 9:17
 */
namespace app\api\controller;

use app\api\model\Bank;
use app\api\model\GetBank;
use app\api\model\Login;
use think\Db;
use think\Request;
use think\Validate;

class Index
{
//    public function ces(){
//        return urlencode('你好啊');
//    }
    /***
     * 处理前台用户注册
     * @param Request $request
     * @return string|\think\response\Json
     */
    public function appreg(Request $request)
    {
        $code = $request->param('code',null);
        if($code){
//            获取微信用户登录信息
            return "111";
        }else{
            $data = $request->param();
            $yanzheng = val($data,[
                'user'  => 'require|max:25|chsDash',
                'pwd'=>'require',
                'email' => 'email',
                'phone' => 'mobile',
                'occupation|职业' => 'require',
                'nickname'        =>'require'
            ]);
            if($data['pwd']!=$data['repwd']){
                return json(['code'=>203,'msg'=>'确认密码错误']);
            }
            unset($data['repwd']);
            if(!$yanzheng["code"]){
                return json(["code"=>401,'msg'=>$yanzheng['msg']]);
            }
            $user = Db::name('user')->where('user',$data['user'])->find();
            if($user){
                return json(['code'=>203,'msg'=>'本账号已经存在']);
            }
            $data["pwd"] = md5(md5($data["pwd"]));
            $data["token"] = md5(uniqid().$data['user']);
            $data["create_time"] = time();
            $data['user_number'] = time().$data['user'];
            $data['extension']   = 0;
            $data['user_name']   = $data['user'];
            $data['vip']   = 12;
            $data['coin']   = 0;
            $data['grade']   = 1;
            $data['experience']   = 0;
            $data['jade']   = 0;
            $data['wisdom']   = 0;
            $data['status']   = 0;
            if(Db::name("user")->insert($data)){
                $user = Db::name('user')->where('user',$data['user'])->find();
                return json(["code"=>200,"msg"=>"注册成功",'user'=>$user]);
            }else{
                return json(["code"=>401,"msg"=>"发生未知错误，请稍后再试"]);
            }
        }
    }

    /***
     * 处理App端前台用户登录
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Applogin(Request $request)
    {
        $data = $request->param();
        $yanzheng = val($data,[
            'user'  => 'require',
            'pwd'=>'require',
        ]);
        if(!$yanzheng){
            return json(["code"=>401,"msg"=>$yanzheng["msg"]]);
        }
        $user = Db::name("user")->where("user",$data["user"])->find();
        if($user&&$user["pwd"]==md5(md5($data["pwd"]))){
            $token  = md5(uniqid().$user["user"]);
            if(Db::name("user")->where("id",$user["id"])->update(["token"=>$token])){
                $user["token"] = $token;
                return json(["code"=>200,"msg"=>"登录成功","user"=>$user]);
            }else{
                return json(["code"=>401,"msg"=>"状态码生成失败，请重试"]);
            }
        }else{
            return json(["code"=>401,"msg"=>"账号或密码有误，请重试"]);
        }
    }

    /***
     * 排行榜
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Rankings(Request $request)
    {
        $user = Login::index($request->param("token",null));
        if(!$user){
        //未登录。返回登录页面
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        $type = $request->param("type",null);
        $page = $request->param('page',1);
        $limit = $request->param('limit',30);
        if(!$type){
            $type = 'grade';
        }
        if($type=='grade'){
            $user_list = Db::name("user")
                ->order("$type desc experience desc")
                ->limit(($page-1)*$limit,$limit)
                ->select();
        }else{
            $user_list = Db::name("user")
                ->order("$type desc")
                ->limit(($page-1)*$limit,$limit)
                ->select();
        }

        //用户自身名次
        $current_user = \app\api\model\Index::paih($user,$type);

        return json(["user"=>$user,"user_list"=>$user_list,"current_user"=>$current_user]);
    }
    /***
     * 获取题目(点击开始考试需要传递参数，点击下一题获取当前题的基本信息通过前台获取)
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBank(Request $request){
        $token = $request->param('token',null);
        $type        = $request->param('type',null);
        $difficulty  = $request->param('difficulty',null);
        $three_level_id = $request->param('three_level_id',null);
        $daojishi       = $request->param('end_time',null);
        $status = $request->param('status',1);
        $user = Login::index($token);
        //获取用户信息
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        //获取$three_level_id，如果没有获取上次上传的
        if(!$three_level_id){
            $id = end($user['answer_number']);
            $bank = Db::name('bank')->where('id',$id)->find();
            $type = $bank['type'];
            $three_level_id = $bank['three_level_id'];
            $difficulty = $bank['difficulty'];
            $daojishi   = $user['end_time'];
        }
        //获取题目
        $data = GetBank::get($three_level_id,$type,$difficulty,$status,$user['answer_number']);
        //获取题目的模式
        $type = Db::name('situation')->where('id',$type)->find();
        //如果是开始做题
//        return 11;
        if(!$user['answer_number']){
            //如果是非会员
            if(!($user['vip_icon']>1&&$type['id']=='1')){
                $datiNum = $type['number']*\app\api\model\Index::sys('shiti');
                if($user['coin']<$datiNum){
                    return json(['code'=>203,'msg'=>'你的金币不足，请充值']);
                }
                $user['coin'] = $user['coin']-$type['number'];
            }
            $daojishi = \app\api\model\Index::sys('kaoshishijian');
        }else{
            if(count($user['answer_number'])==\app\api\model\Index::sys('shiti')){
                return json(['code'=>203,'msg'=>'本次的试题已完成，请结算']);
            }
            if(!($user['vip_icon']>1&&$type['id']=='1')){
                $user['coin'] = $user['coin']-$type['number'];
            }
        }
        //将当前提加入已答题目
        $user['answer_number'][] = $data['id'];
        $tishu  = count($user['answer_number']);
        if($type['id']==\app\api\model\Index::sys('bujishijiandemoshiid')){
            $daojishi = 0;
        }
        if(Db::name('user')->where('id',$user['id'])->json(['answer_number'])->update(['answer_number'=>$user['answer_number'],'coin'=>$user['coin'],'end_time'=>$daojishi])){
            return json(['code'=>200,'data'=>$data,'user'=>$user,'tishu'=>$tishu]);
        }else{
            return json(['code'=>203,'msg'=>'系统错误,请稍后再试']);
        }
    }

    /***处理答题逻辑
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function ifgetBank(Request $request)
    {
        $token = $request->param('token',null);
        $end_time = $request->param("end_time",null);
        $id = $request->param("id",null);
        $right_key = $request->param("right_key",null);
        if(!$id){
            return json(["code"=>401,"msg"=>"缺少必要参数"]);
        }
        if(!$right_key){
            return json(["code"=>401,"msg"=>"请至少选择一个选项"]);
        }
        $user = Login::index($token);
//        echo '<pre>';print_r($user);exit;
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        //获取当前回答的问题
        $ti = Db::name("bank")
            ->where("id",$id)
            ->find();
        $jg = \app\api\model\Index::timu($ti,$user,$right_key,$end_time);
//        echo '<pre>';print_r($jg);exit;
        return json($jg);
    }

    /***
     * 考试结算
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Settlement(Request $request)
    {
        $token = $request->param("token");
        $user = Login::index($token);
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
//        echo '<pre>';print_r($user);exit;
        $tishu = \app\api\model\Index::sys("shiti");
        //错题
        $data["cuoti"] = (int)$tishu - (int)$user["correct"];
        $shijian = \app\api\model\Index::sys("kaoshishijian");
        //用时
        $data["yongshi"] = (int)$shijian - (int)$user["end_time"];
        //百分比
        $data["baifenbi"] = ((int)$user["correct"]/(int)$tishu*100)."%";
        $jigexian = \app\api\model\Index::sys("pass");
        $Ksjiesuan = \app\api\model\Index::Ksjiesuan($user);
        if(!$Ksjiesuan){
            return json(["code"=>401,"msg"=>"系统错误请稍后"]);
        }
        if((int)$user["correct"]>=(int)$jigexian){
            $data['jige'] = 1;
        }else{
            $data['jige'] = 0;
        }
        return json(["code"=>200,"data"=>$data]);
    }

    /***继续完成考试,弹框获取数据
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Continueks(Request $request)
    {
        $token = $request->param("token");
        $user = Login::index($token);
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        if($user["answer_number"]){
            $ti_id = end($user["answer_number"]);
            $ti = (new Bank())->get($ti_id);
            $data["three_level_id"] = $ti['three_level_id'];
            $data['type'] = $ti['type'];
            //完成题数
            $data["num"] = count($user["answer_number"]);
            //所剩时间
            $sj = \app\api\model\Index::sys("kaoshishijian");
            $data["shijian"] = (int)$sj - (int)$user["end_time"];
            return $data;
        }else{
            return false;
        }
    }
    /***补充个人资料
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function ziliao(Request $request)
    {
        $token = $request->param("token");
        $user = Login::index($token);
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        $data = $request->param();
        $vili = val($data,[
            'nickname'  => 'require|max:25|chsAlpha',
            'occupation'=>'require',
            'csrq'  =>'require',
            'email' => 'email',
            'phone' => 'mobile',
        ]);
        if(!$vili){
            return json(["code"=>401,"msg"=>$vili["msg"]]);
        }
        unset($data["token"]);
        if(Db::name("user")->where("id",$user["id"])->update($data)){
            return json(["code"=>200,"msg"=>"成功"]);
        }else{
            return json(["code"=>401,"msg"=>"系统错误"]);
        }
    }

}
